package com.sdp.irrigation.kafka.biz.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.sdp.irrigation.cache.EqRealTimeCache;
import com.sdp.irrigation.db.irrigation_eq_real_time.service.IIrrigationEqRealTimeService;
import com.sdp.irrigation.entity.IrrigationEqRealTime;
import com.sdp.irrigation.kafka.biz.IProtocolBiz;
import com.sdp.irrigation.protocol.CommPackage;
import com.sdp.irrigation.utils.BeanUtils;
import com.sdp.irrigation.utils.CommConstants;
import com.sdp.irrigation.utils.IrrigationConstants;

@Component
public class SetBiz implements IProtocolBiz {

	@Autowired 
	private IIrrigationEqRealTimeService eqRealTimeService;
	
	@Autowired
	private EqRealTimeCache eqRealTimeCache;
	
	@Override
	public void execute(List<CommPackage> packageList) {
		if (packageList.size() > 0) {
			Map<String, IrrigationEqRealTime> eqRealTimeMap = new HashMap<>();
			
			for (CommPackage commPackage : packageList) {
				String devSn = CommConstants.getVersionCommPackageDevSn(commPackage);
				if (!StringUtils.isEmpty(devSn)) {
					IrrigationEqRealTime eqRealTime = eqRealTimeCache.getEqRealTimeCache(devSn);
					if (eqRealTime != null && !StringUtils.isEmpty(eqRealTime.getEqNo())) {
						//设备上报的时间不准，优先使用服务器的更新时间
						eqRealTime.setUpdateTime(LocalDateTime.now());
						eqRealTime.setOnlineStatus(IrrigationConstants.设备在线状态_在线.getCode());
						eqRealTime.setCommandSetStatus(commPackage.getSet());
						
						//新建对象，对缓存进行部分更新
						IrrigationEqRealTime eqRealTimeUpdate = new IrrigationEqRealTime();
						eqRealTimeUpdate.setUpdateTime(eqRealTime.getUpdateTime());
						eqRealTimeUpdate.setOnlineStatus(IrrigationConstants.设备在线状态_在线.getCode());
						eqRealTimeUpdate.setCommandSetStatus(commPackage.getSet());
						
						eqRealTimeCache.updateEqRealTimeCache(devSn, BeanUtils.redisBean2Map(eqRealTimeUpdate));
						
						//更新数据库信息
						if (!eqRealTimeMap.containsKey(devSn)) {
							eqRealTimeMap.put(devSn, eqRealTime);
						}
					}
				}
			}
			
			if (eqRealTimeMap.size() > 0) {
				eqRealTimeService.updateBatchById(new ArrayList<>(eqRealTimeMap.values()));
			}
		}
		
	}

}
